package chapter02;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 两阶段终止案例
 */
@Slf4j
public class TwoPhaseEndTest {
    public static void main(String[] args) throws InterruptedException {
        SystemMonitor systemMonitor = new SystemMonitor();
        systemMonitor.start();
        TimeUnit.MILLISECONDS.sleep(3500);
        systemMonitor.stop();
    }

    static class SystemMonitor{
        private Thread monitor;
        public void start(){
            monitor=new Thread(()->{
                while (true){
                    Thread currentThread = Thread.currentThread();
                    if (currentThread.isInterrupted()){
                        // 线程被打断
                        log.info("线程被打断，处理后事");
                        break;// 跳出循环
                    }
                    try {
                        Thread.sleep(1000);
                        log.info("正在执行监控程序执行");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        currentThread.interrupt();
                    }
                }
            },"monitor");
            monitor.start();
        }
        public void stop(){
            monitor.interrupt();// 打断运行
        }
    }
}
